package com.glory.dgcpcpda.activity.mfg;

import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.UpdateIPEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class UpdateIPActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqp)
    FreeUI_ClearEditText etEqp;
    @BindView(R.id.tvEqpType)
    TextView tvEqpType;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.flEqpIPList)
    FrameLayout flEqpIPList;
    @BindView(R.id.ivEqpTypeArrow)
    ImageView ivEqpTypeArrow;
    @BindView(R.id.etPosition)
    FreeUI_ClearEditText etPosition;
    @BindView(R.id.etIPAddress)
    TextView etIPAddress;
    @BindView(R.id.etPort)
    FreeUI_ClearEditText etPort;
    @BindView(R.id.tvDownLoad)
    TextView tvDownLoad;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.btnCheck)
    Button btnCheck;
//    @BindView(R.id.btnSearch)
//    Button btnSearch;
    @BindView(R.id.etState)
    TextView etState;


    private List<String> mEqpIP = new ArrayList<>();
    private FreeUI_GeneralPop mEqpIPPop;
    private String mEqpip = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_update_ip;
    }

    @Override
    protected void initView() {
        tvBaseSubmit.setVisibility(View.GONE);
        tvTitle.setText("修改设备IP地址");
        setMainLayout(llMain);

        initEdit(etEqp, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {
                FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                        (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                            UpdateIPEntity body = response.body().getResponse().getBody();
                            tvEqpType.setText(body.getEQPTYPE());
                            tvStep.setText(body.getPROCESSNAME());
                            etPosition.setText(body.getPOSITION());
                            mEqpip=body.getIP();
                            etIPAddress.setText("");
//                            etIPAddress.setText(body.getIP());
                            etPort.setText(body.getPort());
                            etState.setText(body.getSTATE());
                            if(body.getSTATE().equals("OFFLINE")){
                                btnCheck.setVisibility(View.VISIBLE);
                            }else{
                                btnCheck.setVisibility(View.GONE);
                            }
                            requestEqpIPList();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "GETEQPINFOBYEQPID");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("EQPID",s);
                NetUtils.requestPostNet("EAP.GETEQPINFOBYEQPID","GETEQPINFOBYEQPID",UpdateIPActivity.this,map,callBack);
            }
        });



//        initEdit(etIPAddress, new editTextListener() {
//            @Override
//            public void onTextChangeListener(String s) {
//                FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
//                        (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
//                        }.getType(), getSupportFragmentManager(), this) {
//
//                    @Override
//                    public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
//                        super.onSuccess(response);
//                        if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
//                            UpdateIPEntity body = response.body().getResponse().getBody();
//                            tvEqpType.setText(body.getEQPTYPE());
//                            tvStep.setText(body.getPROCESSNAME());
//                            etPosition.setText(body.getPOSITION());
//                            etPort.setText(body.getPort());
//                            etState.setText(body.getSTATE());
//                            etEqp.setText(body.getEQPID());
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
//                        super.onError(response);
//                        loadError(response.getException(), "GETEQPINFOBYEQPID");
//                    }
//                };
//
//                JsonObject map = new JsonObject();
//                map.addProperty("IP",s);
//                NetUtils.requestPostNet("EAP.GETIPINFOBYEQPID","GETIPINFOBYEQPID",UpdateIPActivity.this,map,callBack);
//            }
//        });



    }

    //获取维护的IP列表
    private void requestEqpIPList() {
        FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    UpdateIPEntity body = response.body().getResponse().getBody();
                    mEqpIP = body.getList();
                    mEqpIPPop = null;  // 重置菜单
                    //当设备IP与维护IP一致时，显示IP。
                    for(int i=0;i<mEqpIP.size();i++){
                        if(mEqpip.equals(mEqpIP.get(i))){
                            etIPAddress.setText(mEqpIP.get(i));
                            return;
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GetIpListById");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQPID",getText(etEqp));
        NetUtils.requestPostCPC("CPC.GetIpListById","GetIpListById",this,map,callBack);
    }

    @Override
    protected void initData() {

    }


    @OnClick({R.id.tvDownLoad, R.id.btnCheck, R.id.flEqpIPList})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvDownLoad:
                if (actionControl("Submit29"))
                    return;

                IpAddress.IpAdd is = new IpAddress.IpAdd();
                if (!is.isIP(etIPAddress.getText().toString())){
                    showToast("请输入正确的IP地址",false);
                    return;
                }

                if (getText(etEqp).equals("") || etIPAddress.getText().toString().equals("") || getText(etPosition).equals("")){
                    showToast("设备名称、IP地址或设备位置不能为空",false);
                    return;
                }
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                                (new TypeToken<BaseResponseBean<JSONObject>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    showToast("修改成功",true);
                                    clear();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                                super.onError(response);
                                loadError(response.getException(), "ModifyEqpConnection");
                            }
                        };
                        JsonObject map = new JsonObject();
                        map.addProperty("EqpID",getText(etEqp));
                        map.addProperty("PROCESSNAME",tvStep.getText().toString());
                        map.addProperty("EQPTYPE",tvEqpType.getText().toString());
                        map.addProperty("POSITION",getText(etPosition));
                        map.addProperty("IP",etIPAddress.getText().toString());
                        map.addProperty("Port",getText(etPort));
                        NetUtils.requestPostNet("CPC.ModifyEqpConnection","ModifyEqpConnection",this,map,callBack);
                    }
                });
                break;
            case R.id.btnCheck:
                if (etIPAddress.getText().toString().equals("") || getText(etPort).equals("")){
                    showToast("IP地址或端口不能为空",false);
                    return;
                }

                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                                (new TypeToken<BaseResponseBean<JSONObject>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                    showToast(response.body().getResponse().getHeader().getRESULTMESSAGE(),true);
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                                super.onError(response);
                                loadError(response.getException(), "CheckIpPort");
                            }
                        };
                        JsonObject map = new JsonObject();
                        map.addProperty("IP",etIPAddress.getText().toString());
                        map.addProperty("Port",getText(etPort));
                        NetUtils.requestPostCPC("CPC.CheckIpPort","CheckIpPort",this,map,callBack);
                    }
                },"确定要检查IP连通性吗？");
                break;
//            case R.id.btnSearch:
//                if (etIPAddress.getText().toString().equals("")){
//                    showToast("IP地址不能为空",false);
//                    return;
//                }
//
//                showSubmitDialog(new onSubmitListener() {
//                    @Override
//                    public void setOnSubmitListener() {
//                        FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
//                                (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
//                                }.getType(), getSupportFragmentManager(), this) {
//
//                            @Override
//                            public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
//                                super.onSuccess(response);
//                                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
//                                    UpdateIPEntity body = response.body().getResponse().getBody();
//                                    tvEqpType.setText(body.getEQPTYPE());
//                                    tvStep.setText(body.getPROCESSNAME());
//                                    etPosition.setText(body.getPOSITION());
//                                    etPort.setText(body.getPort());
//                                    etState.setText(body.getSTATE());
//                                    etEqp.setText(body.getEQPID());
//                                }
//                            }
//
//                            @Override
//                            public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
//                                super.onError(response);
//                                loadError(response.getException(), "GETEQPINFOBYEQPID");
//                            }
//                        };
//
//                        JsonObject map = new JsonObject();
//                        map.addProperty("IP",etIPAddress.getText().toString());
//                        NetUtils.requestPostNet("EAP.GETIPINFOBYEQPID","GETIPINFOBYEQPID",UpdateIPActivity.this,map,callBack);
//                    }
//                },"确定要查询IP的设备信息吗？");
//                break;
            case R.id.flEqpIPList:
                if (mEqpIP.size() <= 0) {
                    showToast("未获取到设备IP列表", false);
                    return;
                }
                if (mEqpIPPop != null) {
                    if (mEqpIPPop.isShowing()) {
                        mEqpIPPop.dismiss();
                    }
                } else {
                    mEqpIPPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEqpIPList.getWidth(), mEqpIP, ivEqpTypeArrow, (codeS, i) -> {
                        etIPAddress.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivEqpTypeArrow);
                mEqpIPPop.showAsDropDown(flEqpIPList, 0, 0);
                break;
        }



    }

    private void clear() {
        etEqp.setText("");
        tvStep.setText("");
        tvEqpType.setText("");
        etIPAddress.setText("");
        etPosition.setText("");
        etPort.setText("");
        etState.setText("");
    }
}

class IpAddress {
    public static class IpAdd {
        public boolean isIP(String addr) {
            if (addr.length() < 7 || addr.length() > 15 || "".equals(addr)) {
                return false;
            }
/**
 * 判断IP格式和范围
 */
            String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
            Pattern pat = Pattern.compile(rexp);
            Matcher mat = pat.matcher(addr);
            boolean ipAddress = mat.find();
            return ipAddress;
        }
    }
}